# -*- coding: utf-8 -*-
"""
定时任务控制层

负责处理定时任务相关的HTTP请求和响应，包括任务管理、执行监控、配置管理等
"""
from fastapi import APIRouter, HTTPException, Depends, Query, BackgroundTasks
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from datetime import datetime
from app.services.task_service import TaskManagementService
from app.controllers.user_controller import get_current_user

# 创建路由
task_router = APIRouter(
    prefix="/tasks",
    tags=["tasks"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
task_management_service = TaskManagementService()

# Pydantic 模型
class ManualTaskRequest(BaseModel):
    task_name: str = Field(..., description="任务名称")
    task_params: Optional[Dict[str, Any]] = Field(None, description="任务参数")

class TaskConfigRequest(BaseModel):
    task_name: str = Field(..., description="任务名称")
    config: Dict[str, Any] = Field(..., description="任务配置")

class TaskHistoryQueryRequest(BaseModel):
    task_name: Optional[str] = Field(None, description="任务名称筛选")
    task_type: Optional[str] = Field(None, description="任务类型筛选")
    page: int = Field(1, gt=0, description="页码")
    page_size: int = Field(20, gt=0, le=100, description="每页数量")


# =========================== 任务执行接口 ===========================

@task_router.post("/execute")
async def execute_manual_task(
    request: ManualTaskRequest, 
    background_tasks: BackgroundTasks,
    current_user = Depends(get_current_user)
):
    """手动执行任务"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足，只有管理员和销售员可以执行任务")
        
        # 异步执行任务
        def run_task():
            import asyncio
            asyncio.run(task_management_service.execute_manual_task(
                request.task_name, request.task_params
            ))
        
        background_tasks.add_task(run_task)
        
        return {
            "code": 200,
            "message": f"任务 {request.task_name} 已提交执行",
            "data": {
                "task_name": request.task_name,
                "status": "submitted"
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"执行任务失败: {str(e)}")


@task_router.post("/execute-sync")
async def execute_manual_task_sync(
    request: ManualTaskRequest,
    current_user = Depends(get_current_user)
):
    """同步执行任务（等待执行完成）"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足，只有管理员和销售员可以执行任务")
        
        result = await task_management_service.execute_manual_task(
            request.task_name, request.task_params
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"执行任务失败: {str(e)}")


# =========================== 任务历史和监控接口 ===========================

@task_router.get("/history")
async def get_task_execution_history(
    task_name: Optional[str] = Query(None, description="任务名称筛选"),
    task_type: Optional[str] = Query(None, description="任务类型筛选"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(20, gt=0, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取任务执行历史"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        result = task_management_service.get_task_execution_history(
            task_name=task_name,
            task_type=task_type,
            page=page,
            page_size=page_size
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务历史失败: {str(e)}")


@task_router.get("/statistics")
async def get_task_statistics(
    task_type: Optional[str] = Query(None, description="任务类型筛选"),
    days: int = Query(7, ge=1, le=365, description="统计天数"),
    current_user = Depends(get_current_user)
):
    """获取任务统计信息"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        result = task_management_service.get_task_statistics(
            task_type=task_type,
            days=days
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务统计失败: {str(e)}")


# =========================== 任务配置管理接口 ===========================

@task_router.put("/config")
async def update_task_config(
    request: TaskConfigRequest,
    current_user = Depends(get_current_user)
):
    """更新任务配置"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role != 'admin':
            raise HTTPException(status_code=403, detail="权限不足，只有管理员可以修改任务配置")
        
        result = task_management_service.update_task_config(
            request.task_name, request.config
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新任务配置失败: {str(e)}")


# =========================== 任务类型和状态接口 ===========================

@task_router.get("/types")
async def get_task_types(current_user = Depends(get_current_user)):
    """获取任务类型列表"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        task_types = [
            {
                "type": "goods",
                "name": "商品同步",
                "description": "同步商品和品牌信息",
                "tasks": [
                    {"name": "goods_sync", "description": "同步商品数据"},
                    {"name": "goods_brand_sync", "description": "同步商品品牌"}
                ]
            },
            {
                "type": "stock",
                "name": "库存同步", 
                "description": "同步库存变更信息",
                "tasks": [
                    {"name": "stock_sync", "description": "同步库存变更"}
                ]
            },
            {
                "type": "order",
                "name": "订单同步",
                "description": "同步订单和出库单信息",
                "tasks": [
                    {"name": "order_sync", "description": "同步订单数据"}
                ]
            },
            {
                "type": "refund",
                "name": "退款同步",
                "description": "同步退款信息",
                "tasks": [
                    {"name": "refund_sync", "description": "同步退款数据"}
                ]
            },
            {
                "type": "logistics",
                "name": "物流同步",
                "description": "同步物流信息",
                "tasks": [
                    {"name": "logistics_sync", "description": "同步物流数据"}
                ]
            },
            {
                "type": "base_info",
                "name": "基础信息同步",
                "description": "同步基础信息",
                "tasks": [
                    {"name": "base_info_sync", "description": "同步基础信息"}
                ]
            },
            {
                "type": "maintenance",
                "name": "维护任务",
                "description": "系统维护任务",
                "tasks": [
                    {"name": "database_backup", "description": "数据库备份"}
                ]
            }
        ]
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": task_types
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务类型失败: {str(e)}")


@task_router.get("/status")
async def get_task_status_overview(current_user = Depends(get_current_user)):
    """获取任务状态总览"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        # 获取各类型任务的统计信息
        task_types = ['goods', 'stock', 'order', 'refund', 'logistics', 'base_info', 'maintenance']
        status_overview = {}
        
        for task_type in task_types:
            stats_result = task_management_service.get_task_statistics(task_type=task_type, days=1)
            if stats_result['success']:
                status_overview[task_type] = stats_result['data']
            else:
                status_overview[task_type] = {
                    "total_executions": 0,
                    "success_count": 0,
                    "failed_count": 0,
                    "success_rate": 0.0
                }
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "overview": status_overview,
                "last_updated": datetime.now().isoformat()
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务状态总览失败: {str(e)}")


# =========================== 快捷执行接口 ===========================

@task_router.post("/quick/goods-sync")
async def quick_goods_sync(
    enable_batch: bool = Query(False, description="是否启用批量同步"),
    current_user = Depends(get_current_user)
):
    """快捷商品同步"""
    request = ManualTaskRequest(
        task_name="goods_sync",
        task_params={"enable_batch": enable_batch}
    )
    return await execute_manual_task_sync(request, current_user)


@task_router.post("/quick/stock-sync")
async def quick_stock_sync(current_user = Depends(get_current_user)):
    """快捷库存同步"""
    request = ManualTaskRequest(task_name="stock_sync")
    return await execute_manual_task_sync(request, current_user)


@task_router.post("/quick/order-sync")
async def quick_order_sync(current_user = Depends(get_current_user)):
    """快捷订单同步"""
    request = ManualTaskRequest(task_name="order_sync")
    return await execute_manual_task_sync(request, current_user)


@task_router.post("/quick/base-info-sync")
async def quick_base_info_sync(current_user = Depends(get_current_user)):
    """快捷基础信息同步"""
    request = ManualTaskRequest(task_name="base_info_sync")
    return await execute_manual_task_sync(request, current_user)


# =========================== 系统任务状态接口 ===========================

@task_router.get("/scheduler/status")
async def get_scheduler_status(current_user = Depends(get_current_user)):
    """获取定时器调度状态"""
    try:
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role != 'admin':
            raise HTTPException(status_code=403, detail="权限不足，只有管理员可以查看调度器状态")
        
        # 返回手动管理模式的状态
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "mode": "manual_only",
                "scheduler_running": True,
                "total_jobs": 0,
                "active_jobs": 0,
                "auto_tasks_enabled": False,
                "manual_tasks_available": True,
                "next_run_time": None,
                "last_execution": None,
                "message": "🛑 所有定时任务已禁用，只能手动执行",
                "available_manual_tasks": [
                    "goods_sync",
                    "stock_sync", 
                    "order_sync",
                    "refund_sync",
                    "logistics_sync",
                    "base_info_sync",
                    "database_backup"
                ],
                "manual_task_endpoints": [
                    "POST /uniapp/tasks/execute",
                    "POST /uniapp/tasks/execute-sync",
                    "POST /uniapp/tasks/quick/goods-sync",
                    "POST /uniapp/tasks/quick/stock-sync",
                    "POST /uniapp/tasks/quick/order-sync",
                    "POST /uniapp/tasks/quick/base-info-sync"
                ]
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取调度器状态失败: {str(e)}")


# =========================== 兼容老版本API ===========================

# 创建兼容路由
compat_task_router = APIRouter(
    prefix="/task",
    tags=["task-compat"],
    responses={404: {"description": "Not found"}}
)

@compat_task_router.post("/manual-execute")
async def compat_execute_manual_task(
    request: ManualTaskRequest,
    current_user = Depends(get_current_user)
):
    """兼容版本：手动执行任务"""
    return await execute_manual_task_sync(request, current_user)

@compat_task_router.get("/history")
async def compat_get_task_history(
    task_name: Optional[str] = Query(None),
    page: int = Query(1, gt=0),
    page_size: int = Query(20, gt=0, le=100),
    current_user = Depends(get_current_user)
):
    """兼容版本：获取任务历史"""
    return await get_task_execution_history(task_name, None, page, page_size, current_user) 